export const hanleToken = (handle, tokenName, value) => {
	switch (handle) {
	case 'get':
		return uni.getStorageSync(tokenName);
		// break;
	case 'remove':
		return uni.removeStorageSync(tokenName);
		// break;
	case 'set': 
		return uni.setStorageSync(tokenName, value);
		// break;
	}
};
const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : '0' + n;
};
// date 为new Date() 的值 str为分隔符,showHour年月日 时分秒  siginSte=>只显示时分秒
export const formatTime = (times, str, showHour, siginSte) => {
	str = str || '-';
	showHour = showHour || false;
	siginSte = siginSte || false;
	let date = new Date(times);
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	if (siginSte) {
		return (
			[hour, minute, second].map(formatNumber).join(':')
		);
	}
	if (showHour) {
		return (
			[year, month, day].map(formatNumber).join(str) +
			' ' + [hour, minute, second].map(formatNumber).join(':')
		);
	} else {
		return (
			[year, month, day].map(formatNumber).join(str)
		);
	}
};

// 格式化时间
export const dateFormat = function (fmt = 'YYYY-MM-DD', date = new Date()) {
	const time = new Date(date);
	const weekArr = ['日', '一', '二', '三', '四', '五', '六'];
	let o = {
		// 月份
		'M+': time.getMonth() + 1,
		// 日
		'D+': time.getDate(),
		// 小时
		'h+': time.getHours(),
		// 分
		'm+': time.getMinutes(),
		// 秒
		's+': time.getSeconds(),
		// 季度
		'q+': Math.floor((time.getMonth() + 3) / 3),
		// 毫秒
		S: time.getMilliseconds(),
		// 星期
		W: time.getDay(),
	};
	if (/(Y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp('(' + k + ')').test(fmt))
			fmt = fmt.replace(
				RegExp.$1,
				RegExp.$1 == 'W' ?
					weekArr[o[k]] :
					RegExp.$1.length == 1 ?
						o[k] :
						('00' + o[k]).substr(('' + o[k]).length)
			);
	return fmt;
};

export const versionToNum = function (value) {
	const version = value.toString();
	let versionArray = version.split('.');
	// eslint-disable-next-line
	let num_place = ['', '0', '00', '000', '0000'];
	let r = num_place.reverse();
	for (let i = 0; i < versionArray.length; i++) {
		let len = versionArray[i].length;
		versionArray[i] = r[len] + versionArray[i];
	}
	return versionArray.join('');
};

// 两数之间的随机数
export const randomNum = function (min, max) {
	return min + Math.floor(Math.random() * (max - min + 1));
};
// 根据时间戳换算对应时间 
// 参数：hour不显示天数 len:区分 分和分钟 getDay = 1时只显示 天
export const formatSeconds = function (value, len = 0, hour = false, getDay = 0) {
	var theTime = parseInt(value);
	var theTime1 = 0;
	var theTime2 = 0;
	var theTime3 = 0;
	if (theTime >= 60) {
		theTime1 = parseInt(theTime / 60);
		theTime = parseInt(theTime % 60);
		if (theTime1 >= 60) {
			theTime2 = parseInt(theTime1 / 60);
			theTime1 = parseInt(theTime1 % 60);

			if (!hour) {
				if (theTime2 >= 24) {
					theTime3 = parseInt(theTime2 / 24);
					theTime2 = parseInt(theTime2 % 24);
				}
			}
		}
	}
	var result = '';
	let arr = ['分', '分钟'];
	if (theTime > 0) {
		// result = ""+parseInt(theTime)+"秒";
	}
	if (theTime1 > 0) {
		result = '' + parseInt(theTime1) + arr[len] + result;
	}
	if (hour) {
		if (theTime2 > 0) {
			result = '' + parseInt(theTime2) + '小时' + result;
		}
	} else {
		if (theTime2 > 0) {
			result = '' + parseInt(theTime2) + '小时' + result;
		}
		if (theTime3 > 0) {
			result = '' + parseInt(theTime3) + '天' + result;
		}
	}
	if (getDay === 1) {
		if (parseInt(theTime3) === 0) {
			return false;
		}
		return '' + parseInt(theTime3) + '天';
	}

	return result;
};
// 计算日期与单前日期时间差
// di作为一个变量传进来
export function timeDiffFn(d1 = '', min = 0, d2 = '') {
	min || 0;
	// console.log('timeDiffFn','d1:',d1,'d2:',d2)
	// 如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	// 将-转化为/，使用new Date
	let dateBegin = new Date(d1.replace(/-/g, '/'));
	// 获取当前时间
	let dateEnd = new Date(d2.replace(/-/g, '/'));
	// 时间差的毫秒数 min*60*1000,
	let dateDiff = (dateBegin.getTime()) - dateEnd.getTime();
	// 计算出相差天数
	let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));
	// 计算天数后剩余的毫秒数
	let leave1 = dateDiff % (24 * 3600 * 1000);
	// 计算出小时数
	let hours = Math.floor(leave1 / (3600 * 1000));
	// 计算相差分钟数
	// 计算小时数后剩余的毫秒数
	let leave2 = leave1 % (3600 * 1000);
	// 计算相差分钟数
	let minutes = Math.floor(leave2 / (60 * 1000));
	//  // 计算分钟数后剩余的毫秒数
	let leave3 = leave2 % (60 * 1000);
	let seconds = Math.round(leave3 / 1000);
	// console.log(" 相差 " + dayDiff + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒")
	dateBegin = null;
	dateEnd = null;
	return {
		day: dayDiff,
		hours: hours,
		minutes: minutes,
		seconds: seconds,
		dateDiff: dateDiff
	};
}
// 获取当前年月日
export function getNowTime(date, full) {
	let nowDate = date ? new Date(date) : new Date();
	let year = nowDate.getFullYear();
	let month = nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) :
		nowDate.getMonth() + 1;
	let day = nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate
		.getDate();
	let hour = nowDate.getHours() < 10 ? '0' + nowDate.getHours() : nowDate.getHours();
	let min = nowDate.getMinutes() < 10 ? '0' + nowDate.getMinutes() : nowDate.getMinutes();
	let dateStr = year + '-' + month + '-' + day;

	if (full) {
		dateStr = dateStr + ' ' + hour + ':' + min;
	}
	nowDate = null;
	return dateStr;
}
// 节流
export function throttle(func, wait) {
	let timeout;
	return function () {
		let context = this;
		let args = arguments;
		if (!timeout) {
			timeout = setTimeout(() => {
				timeout = null;
				func.apply(context, args);
			}, wait);
		}
	};
}
/* 函数节流*/
export function throttles(fn, interval) {
	// 触发的时间
	let enterTime = 0;
	// 间隔时间，如果interval不传，则默认300ms
	let gapTime = interval || 300;
	return function () {
		var context = this;
		// 第一次函数return即触发的时间
		var backTime = new Date();
		if (backTime - enterTime > gapTime) {
			fn.call(context, arguments);
			// 赋值给第一次触发的时间，这样就保存了第二次触发的时间
			enterTime = backTime;
		}
	};
}

/* 函数防抖*/
export function debounce(fn, interval) {
	var timer;
	// 间隔时间，如果interval不传，则默认1000ms
	var gapTime = interval || 1000;
	return function () {
		clearTimeout(timer);
		var context = this;
		// 保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
		var args = arguments;
		timer = setTimeout(function () {
			fn.call(context, args);
		}, gapTime);
	};
}

// #ifdef H5 
import jsonp from 'jsonp';
// #endif
// 获取地理位置
export function getlocalinfo(latitude, longitude) {
	return new Promise((resolve, reject) => {
		const txUrl = 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude +
			'&key=EOIBZ-QO3A5-HB3II-IVYIZ-EKVXK-NQB2Z';
		const url = `//restapi.amap.com/v3/geocode/regeo?key=${'017a0586f3f283a1b0e15b9f7841e6d7'}&location=${longitude},${latitude}&extensions=all&roadlevel=0`;
		// #ifdef MP-WEIXIN
		uni.request({
			header: {
				'Content-Type': 'application/text'
			},
			url:'https:' + url,
			success: (res) => {
				const data = res.data;
				if (data && data.regeocode) {
					// 请求成功，拿到数据  
					data.regeocode.result = data.regeocode.formatted_address ? { address: data.regeocode.formatted_address } : {};
					resolve(data.regeocode);
				} else {
					// 请求失败 
					reject({});
				}
			},
			fail: (err) => {
				console.log(err, 111);
				resolve({});
			}
		});

		// #endif

		// #ifdef H5  
		if (window.sida && window.sida.regeo) {
			window.sida.regeo({ latitude, longitude },
				result => {
					resolve(result);
				},
				err => {
					reject(err);
				}
			);
		} else {
			jsonp(url, {}, (err, data) => {
				if (data && data.regeocode) {
					// 请求成功，拿到数据  
					data.regeocode.result = data.regeocode.formatted_address ? { address: data.regeocode.formatted_address } : {};
					resolve(data.regeocode);
				} else {
					// 请求失败 
					reject(err);
				}
			});
		}
		// #endif
	});
}
// 计算梯龄
export function getDiffYear(dd) {
	let date = new Date(dd.replace(/-/g, '/'));
	let now = new Date();
	if (!date || !now) {
		return '-';
	}

	let diff = now.getTime() - date.getTime();
	date = null;
	now = null;
	return ((diff / (1000 * 60 * 60 * 24)) / 365).toFixed(1);
}

export function runStr(digit) {
	// 随机字符串Fuc

	if (digit == '' || isNaN(digit)) {
		console.log(digit);
	} else {
		let sourceStr = '0,1,2,3,4,5,6,7,8,9';
		let arrStr = sourceStr.split(',');
		// 定义变量并初始化
		let result = '';
		let index = 0;
		for (let i = 0; i < digit; i++) {
			index = parseInt(Math.random() * arrStr.length);
			result += arrStr[index];
		}
		return result;
	}
}

// 判断某个值是否在数组中
export function valueInArr(list, val) {
	if (list.length) {
		return list.includes(val);
	} else {
		return false;
	}
}
// 去除空的参数
export const removeEmpty = function (obj) {
	let newObj = [Object.keys(obj).forEach((key) => (obj[key] == null || obj[key] == '') && delete obj[key]), obj][1];
	return newObj;
};
// 去除空的参数
export const removeEmptyIsZero = function (obj) {
	Object.keys(obj).forEach((key) => {
		if (obj[key] === null || obj[key] === '') {
			delete obj[key];
		}
	});
	return obj;
};

// 数组对象去重 name:指定属性名去重
export const uniqueArr = function (arr = [], name = '') {
	let obj = {};
	let unArr = [];
	if (arr && arr.length > 0) {
		unArr = arr.reduce((item, next) => {
			if (name) {
				obj[next[name]] ? '' : obj[next[name]] = true && item.push(next);
			} else {
				obj[next.id] ? '' : obj[next.id] = true && item.push(next);
			}
			return item;
		}, []);
	}
	return unArr;
};

// 以下是获取本月,本周,范围的函数
// 当前日期
var now = new Date();
// 今天本周的第几天
var nowDayOfWeek = now.getDay();
// 当前日
var nowDay = now.getDate();
// 当前月
var nowMonth = now.getMonth();
// 当前年
var nowYear = now.getFullYear();
// 获得某月的天数
const getMonthDays = (myMonth) => {
	var monthStartDate = new Date(nowYear, myMonth, 1);
	var monthEndDate = new Date(nowYear, myMonth + 1, 1);
	var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
	return days;
};
// 本周时间范围
export const getWeekDate = () => {
	let startDate = new Date(nowYear, nowMonth, nowDay - (nowDayOfWeek - 1));
	let endDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek));

	return {
		startDate,
		endDate
	};
};
// 获取本月时间范围
export const getMonthDate = () => {
	let startDate = new Date(nowYear, nowMonth, 1);
	let endDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
	return {
		startDate,
		endDate
	};
};

// 获取几天前的日期
export const getBeforeDate = (n) => {
	// var n = n;
	// 1 取今天时间
	if (n == 1) {
		n = 0;
	}
	var d = new Date();
	var year = d.getFullYear();
	var mon = d.getMonth() + 1;
	var day = d.getDate();
	if (day <= n) {
		if (mon > 1) {
			mon = mon - 1;
		} else {
			year = year - 1;
			mon = 12;
		}
	}
	d.setDate(d.getDate() - n);
	year = d.getFullYear();
	mon = d.getMonth() + 1;
	day = d.getDate();
	let s = year + '-' + (mon < 10 ? ('0' + mon) : mon) + '-' + (day < 10 ? ('0' + day) : day);
	return s;
};

// 判断两个日期相差多少天
export const getDays = (strDateStart, strDateEnd) => {
	let strSeparator = '-';
	// 日期分隔符   var oDate1;   var oDate2;   
	let iDays;
	let oDate1 = strDateStart.split(strSeparator);
	let oDate2 = strDateEnd.split(strSeparator);
	let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
	let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
	iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24);
	// 把相差的毫秒数转换为天数   
	return iDays;
};

export function getRepairDate(date) {
	if (!date) {
		return {
			year: '',
			date: ''
		};
	}
	let d = date.replace(/-/g, '/');
	let dates = new Date(d);
	const y = dates.getFullYear();
	let m = dates.getMonth() + 1;
	let da = dates.getDate();
	const h = dates.getHours() < 10 ? ('0' + dates.getHours()) : dates.getHours();
	const f = dates.getMinutes() < 10 ? ('0' + dates.getMinutes()) : dates.getMinutes();
	dates.setHours(0, 0, 0, 0);
	let today = new Date().setHours(0, 0, 0, 0);
	const dff = dates - today;
	let dateName = '';
	if (dff == 1000 * 60 * 60 * 24) {
		dateName = '(明天)';
	}
	if (dff == 1000 * 60 * 60 * 24 * 2) {
		dateName = '(后天)';
	}
	if (dff == 0) {
		dateName = '(今天)';
	}
	dates = null;
	today = null;
	return {
		year: y + '年',
		date: m + '月' + da + '日' + dateName + '' + h + ':' + f,
		str: y + '年' + m + '月' + da + '日' + dateName + '' + h + ':' + f,
	};
}

export const reSetNumber = (n) => {
	n = n.toString();
	return n[1] ? n : '0' + n;
};
// 是否电话号码
export function isMobile(s) {
	return /^0\d{2,3}-?\d{7,8}$/.test(s);
}

/**
 * 检查传入的URL是否为常见的图片链接。
 * @param {string} url - 待检查的URL字符串。
 * @returns {boolean} - 如果URL的扩展名是常见的图片格式，则返回true，否则返回false。
 */
export const isImageLink = (url) => {
	// 常见的图片格式列表
	const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
	// 将URL转换为小写，并分割为数组，仅取最后一部分（即扩展名）
	const extension = url.split('.').pop().toLowerCase();
	// 检查扩展名是否在图片格式列表中
	return imageExtensions.includes(extension);
};
/**
 * 检查传入的文件是否为图片文件。
 * @param {File} file - 待检查的URL字符串。
 * @returns {boolean} - 如果URL的扩展名是常见的图片格式，则返回true，否则返回false。
 */
export const isImageFile = (file) => {
	// 获取文件的 MIME 类型
	const mimeType = file.type;
	// 检查 MIME 类型是否以 "image/" 开头
	return mimeType.startsWith('image/');
};
/**
 * 检查提供的链接是否为视频链接。
 * @param {string} link - 待检查的链接。
 * @returns {boolean} 如果链接的文件扩展名在视频扩展名列表中，则返回true；否则返回false。
 */
export const isVideoLink = (url) => {
	// 定义支持的视频文件扩展名列表
	const videoExtensions = ['mp4', 'webm', 'ogg', 'mkv', 'avi', 'wmv', 'mov', 'flv'];
	// 从链接中提取文件扩展名，并转换为小写
	const extension = url.split('.').pop().toLowerCase();
	// 检查提取的扩展名是否在支持的视频扩展名列表中
	return videoExtensions.includes(extension);
};

export const mergeList = (existingList, newRecords,key = 'id') => { 
	// 创建现有数据的 Map，key 为 id，value 为 { item, index }
	const existingMap = new Map();
	existingList.forEach((item, index) => {
		existingMap.set(item[key], { item, index });
	});
		
	// 记录操作统计
	let updateCount = 0;
	let insertCount = 0;
	const result = [...existingList]; // 复制现有列表
		
	newRecords.forEach(newRecord => {
		if (existingMap.has(newRecord[key])) {
			// ID 存在，更新现有记录
			const { index } = existingMap.get(newRecord[key]);
			result[index] = { ...result[index], ...newRecord }; // 合并更新，保留原有字段
			updateCount++;
		} else {
			// ID 不存在，添加新记录
			result.push(newRecord);
			insertCount++;
		}
	});
		
	console.log(`合并完成 - 更新: ${updateCount}条, 新增: ${insertCount}条, 总计: ${result.length}条`);
	return result;
};
